var fs=require("fs");

/**
 * Function: escape_text
 */
function escape_text(text)
{
	if (text===undefined || text===null) return "";
	if (typeof (text)=="number") return text.toString();
	text=text.replace(/\\/g,'\\\\');
	text=text.replace(/"/g,'\\"');
	text=text.replace(/'/g,"\\'");
	text=text.replace(/\r?\n/g,'\\n');
	text=text.replace(/\r/g,'\\n');
	return text;
}

/**
 * Function: escape_text2
 */
function escape_text2(text)
{
	if (text===undefined || text===null) return "";
	if (typeof (text)=="number") return text.toString();
	text=text.replace(/&/g,'&amp;');
	text=text.replace(/</g,'&lt;');
	text=text.replace(/>/g,"&gt;");
	return text;
}

/**
 * Function: O_any
 */
function O_any(opt1,groupped,sel)
{
	var r="";
	var cache=[];
	function nbsps(l)
	{
		if (l==0) return "";
		if (!cache[l]) {
			var tmp="";
			for (var j=0;j<l*3;j++) tmp+=String.fromCharCode(160);
			cache[l]=tmp;
		}
		return cache[l];
	}
	function add_options(opt,baselevel)
	{
		for (var i=0;i<opt.length;i++) {
			var name=escape_text2(opt[i].name);
			var id=escape_text(opt[i].id);
			var l=(opt[i].level||1)+baselevel-1;
			r+='<option value="'+id+'"'+((sel && (id==sel))?" selected":"")+'>'+nbsps(l)+name+'</option>';
		}
	}
	function add_rec(arr,level)
	{
		for (var i=0;i<arr.length;i++) {
			var name=escape_text2(arr[i].label);
			r+='<optgroup label="'+nbsps(level)+name+'">';
			if (arr[i].optgroups) add_rec(arr[i].optgroups,level+1);
			if (arr[i].options) add_options(arr[i].options,level);
			r+='</optgroup>';
		}

	}
	if (groupped) {
		add_rec(opt1,0);
	} else {
		add_options(opt1,0);
	}
	return r;
}


/**
 * Function: locale_load
 *		Loads locale
 *
 * Parameters:
 *		config					- site config or system config
 *		lang typeof String		- language code, i.e. "ru", "en"
 *
 */
function locale_load(config,lang)
{
	if (config.i18n && config.i18n[lang]) return;
	var ret;
	var arr=config.paths.i18n;
	if (arr.constructor!==Array) arr=[arr];
	for (var i=0;i<arr.length;i++) {
		var f=new fs.File(config.paths.i18n[i]+lang+".js");
		if (!f.exists()) continue;
		var req=require(f.toString());
		if (!ret) {ret=req.i18n;continue;}
		for (var k1 in req.i18n) {
			if (!ret[k1]) ret[k1]={};
			for (var k2 in req.i18n[k1]) ret[k1][k2]=req.i18n[k1][k2];
		}
	}
	if (!config.i18n) config.i18n={};
	config.i18n[lang]=ret || {};
}

exports.add=[{
	_type:"functions",
	_section:"Views",

	/**
 	 * Function: Views.ADMINGETL
	 */
	ADMINGETL: function(param,value) {
		return value.l10ns[this.l10n.id][param];
	},

	/**
 	 * Function: Views.HRtoCOLS
	 */
	HRtoCOLS: function(value) {
		if (value==null || value==undefined) return '<div class="cols"><div class="cl"></div></div>';
		return '<div class="cols"><div class="col">'+value.replace(/<hr.*?>/ig,'</div><div class="col">')+'</div><div class="cl"></div></div>';
	},

	/**
 	 * Function: Views.JSONFMT
	 */
	JSONFMT:function(value) {
		if (value==undefined) return "undefined";
		return JSON.stringify(value,undefined,2).replace(/<\/script>/g,'</"+"script>').replace(new RegExp(String.fromCharCode(0x2028),"g"),"");
	},
	/**
 	 * Function: Views.JSON
	 */
	JSON:function(value) {
		if (value==undefined) return "undefined";
		return JSON.stringify(value).replace(/<\/script>/g,'</"+"script>').replace(new RegExp(String.fromCharCode(0x2028),"g"),"");
	},

/*	JSON_select:function(param,values) {
		var ret=[];
		if (param) ret.push({id:"",name:""});
		JSON_select_recurse(param,values,ret,1);
		return space.functions.JSON(space,ret);
	},

	JSON_gridrower:function(space,param,values) {
		var ret=[];
		JSON_gridrower_recurse(space,param.split(/,/),values,ret,1);
		return space.functions.JSON(space,ret);
	},*/

	/**
 	 * Function: Views.ADD
	 */
	ADD: function(param,value) {
		return 1*param+1*value;
	},
	
	/**
 	 * Function: Views.SUB
	 */
	SUB: function(param,value) {
		return -1*param+1*value;
	},

	/**
 	 * Function: Views.MUL
	 */
	MUL: function(param,value) {
		return param*value;
	},

	/**
 	 * Function: Views.MUL1
	 */
	MUL1: function(param,value) {
		return param*(value-1);
	},

	/**
 	 * Function: Views.CROP
	 */
	CROP: function (size,text) {
		if (text==null || text==undefined) return "";
		if (typeof text != "string") text=text.toString();
		if (text.length>size) return text.substr(0,size-3)+"...";
		return text;
	},

	/**
 	 * Function: Views.LI
	 */
	LI: function(value) {
		if (value==null || value==undefined) return "";
		if (typeof value!= "string") value=value.toString();
		value=value.replace(/&/g,'&amp;');
		value=value.replace(/</g,'&lt;');
		value=value.replace(/>/g,'&gt;');
		return "<li>"+value.replace(/\n/g,"</li><li>")+"</li>";
	},

	/**
 	 * Function: Views.B
	 */
	B: function(value) {
		if (value==undefined || value==null) return "";
		value=value.toString();
		value=value.replace(/&/g,'&amp;');
		value=value.replace(/</g,'&lt;');
		value=value.replace(/>/g,'&gt;');
		value=value.replace(/\n/gi,'<br/>');
		return value;
	},

	/**
 	 * Function: Views.MinusTags
	 */
	MinusTags: function(value) {
		value=value.replace(/&lt;(\/?)([biua]|h\d)&gt;/ig,function(a,p1,p2) { return "<"+p1+p2+">";});
		value=value.replace(/&lt;a\s+href="(\/[^"]*|http:[^"]*)"&gt;/ig,function(a,p1) { return "<a href=\""+p1+"\">";});
		return value;
	},

	/**
 	 * Function: Views.Bminus
	 */
	Bminus: function(value) {
		var r=this.F("Views","B",value);
		return this.F("Views","MinusTags",r);
	},

	/**
 	 * Function: Views.P
	 */
	P: function(value) {
		if (value==undefined) return "";
		value=value.replace(/&/g,'&amp;');
		value=value.replace(/</g,'&lt;');
		value=value.replace(/>/g,'&gt;');
		value=value.replace(/\n/gi,'</p>\n<p>');
		return value;
	},

	/**
 	 * Function: Views.Pminus
	 */
	Pminus: function(value) {
		var r=this.F("Views","P",value);
		return this.F("Views","MinusTags",r);
	},

	/**
 	 * Function: Views.T
	 */
	T: function(value) {
		if (value==undefined) return "";
		value=value.replace(/&/g,'&amp;');
		value=value.replace(/</g,'&lt;');
		value=value.replace(/>/g,'&gt;');
		return value;
	},

	/**
 	 * Function: Views.I
	 */
	I: function(value) {
		if (value==undefined) return "";
		value=value.replace(/&/g,'&amp;');
		value=value.replace(/</g,'&lt;');
		value=value.replace(/>/g,'&gt;');
		value=value.replace(/"/g,'&quot;');
		return value;
	},
	
	/**
 	 * Function: Views.JS
	 */
	JS: function(value) {
		if (value==undefined) return "";
		if (typeof(value)=="string") value=escape_text(value).replace(/(scr)(ipt)/gi,'$1"+"$2');
		return value;
	},

	/**
 	 * Function: Views.DumpierNoPre
	 */
	DumperNoPre: function(value) {
		return this.Dumper(value);
	},
	
	/**
 	 * Function: Views.Dumper
	 */
	Dumper: function(value) {
		return "<pre>"+this.Dumper(value)+"</pre>";
	},
	
	/**
 	 * Function: Views.process
	 */
	process: function(value) {
		if (value==undefined) return "";
		if (value==null) return "";
		return this.view_apply(value);
	},

	/**
 	 * Function: Views.CHK
	 */
	CHK: function(value) {
		return value?" checked":"";
	},

	/**
 	 * Function: Views.O
	 */
	O: function(vals) {
		if (!vals) return "";
		return O_any(vals,0);
	},
	
	OSEL: function(sel,vals) {
		if (!vals) return "";
		return O_any(vals,0,sel);
	},

	/**
 	 * Function: Views.OGRP
	 */
	OGRP: function(vals) {
		if (!vals) return "";
		return O_any(vals,1);
	},
	
	/**
 	 * Function: Views.L
	 * Parameters:
	 *		grp typeof String				-
	 *		val typeof String				-
	 *		easyDefault typeof Integer		- 0=returns error, 1=tries ("generic",val,2), 2=returns val, 3=returns undefined
	 */
	L: function(grp,val,easyDefault) {
		var lang=this.use_language;
		if (!lang && this.site) lang=this.site.language;
		if (!lang) lang=this.system.language;
		if (this.site && (!this.site.i18n || !this.site.i18n[lang])) locale_load(this.site,lang);
		if (!this.system.i18n || this.system.i18n[lang]) locale_load(this.system,lang);

		while (1) {
			if (this.site && this.site.i18n[lang][grp] && this.site.i18n[lang][grp][val]) return this.site.i18n[lang][grp][val];
			if (this.system && this.system.i18n[lang][grp] && this.system.i18n[lang][grp][val]) return this.system.i18n[lang][grp][val];
			if (easyDefault==3) return undefined;
			if (easyDefault==2) return val;
			if (easyDefault==1) return this.F("Views","L","generic",val,2);
			return "[I18N("+lang+") "+grp+"."+val+"]";
		}
	},
	
	/**
 	 * Function: Views.preview
	 */
	preview: function(param,value) {
		if (value==null || value==undefined) return "";
		if (param=="" || param==null || param==undefined) return value;
		var arr=value.match(/^(.*)(\.\w+)$/);
//		if (arr[2].match(/^(avi|flv|mpg|mkv|mp4)$/)) arr[2]="jpg";
		return arr[1]+"-preview"+param+arr[2];
	},
	
	/**
 	 * Function: Views.replace
	 */
	replace: function(param,value) {
		var re=new RegExp(param.source);
		return value.replace(re,param.destination);
	},

	
	/**
 	 * Function: Views.match
	 */
	match: function(param,value) {
		var re=new RegExp(param);
		return value.match(re);
	},
	
	
	/**
 	 * Function: Views.full_replace
 	 * 
 	 *		передаем два текстовых параметра в виде строки с разделителем ","
 	 *		ищем совпадение первого параметра и если оно есть возвращаем второй параметр
 	 *		пример: {{full_replace("menu,itemA"):pageinfo.alias}}
 	 *		
	 */
	full_replace: function(param,value) {
		var re = param.split(',')[0];
		var rep = param.split(',')[1];
		return value.match(re)?rep:'';
	},

	/**
 	 * Function: Views.format
	 */
	format: function(param,value) {
		if (typeof value=="null" || typeof value=="undefined" || (typeof value=="string" && value=="")) return "";
		var val=""+value;
		var arr;
		if (!(arr=val.match(/^(-?)(\d+)((?:\.\d+)?)$/))) return value;
		var sign=arr[1];
		var intpart=arr[2];
		var floatpart=arr[3];
		arr=param.match(/^(\d+)G(\d+)C?$/);
		var intsize=1*arr[1];
		var floatsize=1*arr[2];
		while (intpart.length<intsize) intpart="0"+intpart;
		var intpart2="";
		while (intpart.length>3) {
			if (intpart2.length) intpart2=" "+intpart2;
			intpart2=intpart.substr(intpart.length-3,3)+intpart2;
			intpart=intpart.substr(0,intpart.length-3);
		}
		if (intpart2.length) intpart2=" "+intpart2;
		intpart2=intpart+intpart2;
		if (floatsize==0) return sign+intpart2;
		var floatpart2=floatpart.replace(/^\./,"");
		if (floatpart2.length>floatsize) {
			floatpart2=floatpart2.substr(0,floatsize);
		} else {
			while (floatpart2.length<floatsize) floatpart2+="0";
		}
		return sign+intpart2+(param.match(/C/)?",":".")+floatpart2;
	},

	shortmoney: function(amount) {
		amount = parseInt(amount) || 0;
		var mult = '';
		if (amount > 10000) {
			mult = 'k';
			amount = Math.floor(amount / 1000);

			if (amount > 1000) {
				mult = 'kk';
				amount = Math.floor(amount / 1000);
			}
		}

		return this.F('Views', 'format', '0G0', amount) + mult;
	},

	/**
	 * Function: Views.page_block
	 *		Returns page block
	 *		Can be called from templates as {{page_block("abstract_block"):page.id}}
	 *
	 * Parameters:
	 *		place_code typeof String		- value from Ttemplate_places.code
	 *		page_id typeof Integer			- value from Tpages.id
	 */
	page_block: function(place_code,page_id) {
		var pblock,a,i,l10n_id;
		i=0;
		while (!a && i<2) {
			if (i==0) l10n_id=this.site.default_l10n_id; else l10n_id=this.site.fallback_l10n_id;
			i++;
			if (!l10n_id) continue;
			pblock=this.site.sql.execute_and_fetch_one("page_blocks/get_fallback_for_page",{page_id: page_id,place_code:place_code,l10n_id:l10n_id,medium_id:1});
			if (pblock) {
				a=pblock.body;
				if (a=="<p></p>") a=null;
			}
		}
		if (!a) return "";
		if (pblock.preprocess) a=this.views.apply(a,this);
		return a;
	},

    /**
 	 * Function: Views.translit
	 */
	translit: function(value) {
		throw new Error("TODO");/*
		my ($tmpl,$space,$query,$name)=@_;
	$name=new Unicode::Transliterate(from=>"Any",to=>"Latin")->process($name);
	Encode::_utf8_on($name);
	$name=~s/[šŝ]/sh/g;
	$name=~tr/â/ja/;
	$name=~tr/č/ch/;
	$name=~tr/Â/JA/;
	$name=~tr/Č/CH/;
	$name=~tr/éèžû/eezu/;
	$name=~tr/ÉÈŽÛ/EEZU/;
	return $name;*/
	},
	 /**
 	 * Function: Views.CL
 	 *		выводит o в консольную строку браузера
 	 * 
	 */	
	CL: function(o){
		return '<script>console.log('+JSON.stringify(o)+')</script>';
	},
	
	/**
 	 * Function: Views.CF
 	 * 	clear format
	 */
	CF: function(value) {
		if (value==undefined || value==null) return "";
		value=value.toString();
		value=value.replace(/<.+?>/g,'');
		return value;
	},

	/**
 	 * Function: Views.URC
	 */
	URC: function(str) {
		return encodeURIComponent(str);
	},
}];

